using Nancy;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PC.Client
{
    public class HomeModule : NancyModule
    {
        public HomeModule()
        {
            Get("/", x => "欢迎使用电脑控制 -- by 王大锤 \r\n" +
            "关机(post)：/api/shutdown \r\n" +
            "重启(post)：/api/restart \r\n" +
            "注销(post)：/api/logout \r\n" +
            "锁定(post)：/api/lock \r\n" +
            "截屏(post)：/api/screenshot \r\n" +
            "息屏(post)：/api/closemonitor \r\n");
            Get("/api/gettoken", x =>
            {
                return true;
            });
            Post("/api/shutdown", x =>
            {
                ProcessHelper.ShutDown();
                return "shutdown";
            });
            Post("/api/restart", x =>
            {
                ProcessHelper.Restart();
                return "restart";
            });
            Post("/api/logout", x =>
            {
                ProcessHelper.Logout();
                return "logout";
            });
            Post("/api/lock", x =>
            {
                ProcessHelper.Lock();
                return "lock";
            });
            Post("/api/screenshot", x =>
            {
                Bitmap bitmap = ProcessHelper.ScreenShot();
                return ImgToBase64String(bitmap);
            });
            Post("/api/closemonitor", x =>
            {
                ProcessHelper.CloseMonitor();
                return "closemonitor";
            });
        }

        public string ImgToBase64String(Bitmap bmp)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

    }
}
